package com.demo.study.behavior.d02_command.controller;

import com.demo.study.behavior.d02_command.controller.empty.EmptyCommand;
import com.demo.study.behavior.d02_command.controller.light.LightOffCommand;
import com.demo.study.behavior.d02_command.controller.light.LightOnCommand;
import com.demo.study.behavior.d02_command.controller.light.LightReceiver;
import com.demo.study.behavior.d02_command.controller.tv.TvOffCommand;
import com.demo.study.behavior.d02_command.controller.tv.TvOnCommand;
import com.demo.study.behavior.d02_command.controller.tv.TvReceiver;

/**
 * 遥控器
 *
 * @author Baymax
 * @since 2022/3/25
 */
public class RemoteController {
    private Command[] onCommand;
    private Command[] offCommand;
    private Command undoCommand;

    /**
     * 初始化遥控器
     *
     * @param typeNums 支持的操作类型个数
     */
    public RemoteController(int typeNums) {
        initCommand(typeNums);
        for (int i = 0; i < typeNums; i++) {
            onCommand[i] = new EmptyCommand();
            offCommand[i] = new EmptyCommand();
        }
    }

    private void initCommand(int typeNums) {
        onCommand = new Command[typeNums];
        offCommand = new Command[typeNums];
        undoCommand = new EmptyCommand();
    }

    /**
     * 给遥控器的按钮绑定功能
     */
    public void setButtonAction(int num, Command onCommand, Command offCommand) {
        this.onCommand[num] = onCommand;
        this.offCommand[num] = offCommand;
    }

    public void onButton(int num) {
        onCommand[num].execute();
        undoCommand = onCommand[num];
    }

    public void offButton(int num) {
        offCommand[num].execute();
        undoCommand = offCommand[num];
    }

    public void undoButton() {
        undoCommand.undo();
    }

    /**
     * 初始化数据绑定
     *
     * @return 构造好的控制者
     */
    public static RemoteController intiRemoteController() {
        RemoteController remoteController = new RemoteController(5);
        LightReceiver lightReceiver = new LightReceiver("海尔");
        remoteController.setButtonAction(0, new LightOnCommand(lightReceiver), new LightOffCommand(lightReceiver));

        TvReceiver tvReceiver = new TvReceiver("长虹");
        remoteController.setButtonAction(1, new TvOnCommand(tvReceiver), new TvOffCommand(tvReceiver));
        return remoteController;
    }
}
